package com.fast.common.base;

import com.fast.common.util.CommonUtil;
import com.fast.common.util.StringEscapeEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Title：基础控制器
 * @author：ylc
 * @date：2018/7/20 16:21
 * @version：1.0
 **/
public class BaseController {
    /**
     * ThreadLocal确保高并发下每个请求的request，response都是独立的
     */
    private static ThreadLocal<ServletRequest> currentRequest = new ThreadLocal<ServletRequest>();
    private static ThreadLocal<ServletResponse> currentResponse = new ThreadLocal<ServletResponse>();

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }

    /**
     * 线程安全初始化reque，respose对象
     *
     * @param request
     * @param response
     */
    @ModelAttribute
    public void initReqAndRep(HttpServletRequest request, HttpServletResponse response) {
        currentRequest.set(request);
        currentResponse.set(response);
    }

    public HttpServletRequest request() {
        return (HttpServletRequest) currentRequest.get();
    }

    public HttpServletResponse response() {
        return (HttpServletResponse) currentResponse.get();
    }

    protected String getPrefix() {
        return "";
    }

    /**
     * 默认的form表单视图
     *
     * @param model
     * @param id
     * @return
     */
    @GetMapping(value = "/formView")
    protected String formView(Model model, @RequestParam(value = "id", required = false) Long id) {
        model.addAttribute("id", CommonUtil.properIsNULL(id) ? null : String.valueOf(id));
        return getPrefix() + "form";
    }

    /**
     * 默认的主列表页面
     *
     * @param model
     * @return
     */
    @GetMapping(value = "/listView")
    protected String listView(Model model) {
        return getPrefix() + "list";
    }
}
